#!/usr/bin/python
# -*- coding：utf-8 -*-


import pandas as pd
import numpy as np
import datetime
import  csv
import requests
import  demjson
import os
import xgboost as xgb
from sklearn.model_selection import KFold, cross_val_score as CVS, train_test_split as TTS
from time import time
from sklearn.metrics import mean_squared_error as MSE, r2_score
import pickle

DIR = os.path.dirname(os.path.abspath(__file__))
# pre函数，预测函数，无返回值，只需要根据输入的路径来输出一个预测结果的csv文件
def pre(input_path = os.path.join(DIR,"../data/prehour.csv"), output_path = os.path.join(DIR,"../data/ycnl.json"), model_path=os.path.join(DIR,"../model/nlxgboost.dat")):
    # 读取路径中的文件
    data = pd.read_csv(input_path,engine='python', encoding="utf_8_sig")
    data = data.rename(columns={'temp': 'tempavg'})
    data['tempavg'] = data['tempavg'].astype('int')
    data['temphigh'] =data['tempavg']+3
    data['templow'] = data['tempavg'] - 3
    data['SDATE'] = pd.to_datetime(data['SDATE'])
    data = data.loc[(data['SDATE'].dt.hour.isin([0, 6, 12, 18])) & (data['SDATE'].dt.minute == 0)]
    data.index = range(data.shape[0])  # 重置索引
    data['hour'] = data['SDATE'].dt.hour
    data.dropna(inplace=True)
    dataset=pd.DataFrame({'temphigh':data['temphigh'],'templow':data['templow'],
                          'is_holiday':data['is_holiday'],'wind':data['wind'],
                          'humidity': data['humidity'],'tempavg':data['tempavg'],
                          'hour': data['hour']})
    # 导入模型
    loaded_model = pickle.load(open(model_path, "rb"))
    # 做预测，直接调用接口predict
    # ypreds = loaded_model.predict(X_validation)
    yc = xgb.DMatrix(dataset,np.arange(dataset.shape[0]))
    ypreds = loaded_model.predict(yc)
    data = pd.DataFrame({ 'nl':ypreds},index=data['SDATE'].tolist())
    data = data.resample('D').sum()
    data['SDATE'] = data.index
    data['SDATE'] =data['SDATE'].astype('str')
    data.index=data['SDATE']
    data = data.drop(['SDATE'], axis=1)
    if os.path.exists(output_path):
        data.to_json(output_path)
    else:
        data.to_json(output_path)
    

if __name__ == '__main__':
    pre(input_path = os.path.join(DIR,"../data/prehour.csv"), output_path = os.path.join(DIR,"../data/ycnl.json"))